package com.sgb.kjwl.view.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.databinding.DataBindingUtil;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.BuildConfig;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityPreferredChoiceBinding;
import com.sgb.kjwl.di.home.DaggerHomeComponent;
import com.sgb.kjwl.di.home.HomeModule;
import com.swgk.core.view.entity.ChannelEntity;
import com.sgb.kjwl.utils.UpdateUtils;
import com.sgb.kjwl.view.ui.adapter.DragAdapter;
import com.sgb.kjwl.view.ui.adapter.OtherAdapter;
import com.sgb.kjwl.view.widget.BusinessTipsDialog;
import com.sgb.kjwl.view.widget.DragGrid;
import com.sgb.kjwl.viewmodel.home.PreferredChoiceModel;
import com.swgk.core.base.aroute.AppRouteConstant;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.mmkvutil.CacheMarker;
import com.swgk.core.mmkvutil.DatalUtils;
import com.swgk.core.mmkvutil.MkvUtils;
import com.swgk.core.util.MToast;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.inject.Inject;

/**
 * 首次预选界面
 */
@Route(path = AppRouteConstant.PreferredChoiceActivity)
public class PreferredChoiceActivity extends AppActivity {

    private ActivityPreferredChoiceBinding binding;

    @Inject
    PreferredChoiceModel viewModel;

    //private String mChannelName = "首页推荐"; //默认推荐项
    private int mChannelId = 21; //默认首页推荐项
    boolean isMove = false;

    private static Handler handler = new Handler();
    /**
     * 可拖拽
     */
    private DragAdapter selectAdapter;
    private ArrayList<ChannelEntity> selectlList = new ArrayList<>();


    private OtherAdapter otherAdapter;
    private ArrayList<ChannelEntity> otherChannelList = new ArrayList<>();
    private ArrayList<ChannelEntity> jumpToList = new ArrayList<>();

    public static void start(Context context, boolean flag) {
        Intent intent = new Intent();
        intent.setClass(context, PreferredChoiceActivity.class);
        intent.putExtra("isFirst", flag);
        context.startActivity(intent);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerHomeComponent.builder().appComponent(appComponent).homeModule(new HomeModule(this)).build().inject(this);
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(PreferredChoiceActivity.this, R.layout.activity_preferred_choice);
        binding.setViewModel(viewModel);
        //binding.otherGridView.setOnItemClickListener(this);
        //binding.selectGridView.setOnItemClickListener(this);
        binding.btComplete.setOnClickListener(this);
        //binding.jumpOver.setOnClickListener(this);
        binding.btComplete.setSelected(false);
        int screenWidth = getWindowManager().getDefaultDisplay().getWidth();
        // Log.i("xxx",screenWidth/4+" ========"+Px2Dp(this,screenWidth/4) );
        int n = screenWidth / Dp2Px(this, 90);
        binding.otherGridView.setNumColumns(n);
        binding.selectGridView.setNumColumns(n);

        //每一次进入该界面都重置该状态
        MkvUtils.get().putBoolean(MkvUtils.CommomData, CacheMarker.CacheForTheFirstTime, true);
    }

    public int Dp2Px(Context context, float dp) {
        final float scale = context.getResources().getDisplayMetrics().density; //当前屏幕密度因子
        return (int) (dp * scale + 0.5f);
    }

    @Override
    protected void init() {
        viewModel.getChannelData();
        if (BuildConfig.BUILD_TYPE.equals("release")) {
            UpdateUtils.getInstance().getNewVersion(this, false);
        }
    }

    @Override
    protected boolean statusBarDark() {
        return true;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.jump_over:
                jumpActivity(true);
                break;
            case R.id.bt_complete:
                if (selectAdapter.getChannnelLst().size() > 0) {
                    jumpActivity(false);
                } else {
                    //Toast.makeText(this, "请选择您关注的经营业务或跳过此步骤", Toast.LENGTH_SHORT).show();
                    jumpActivity(true);
                }
                break;
            default:
                break;
        }
    }

    /**
     * 跳转至主页面
     */
    private void jumpActivity(boolean isJumpt) {
        if (isJumpt) {
            upDataList2();
        } else {
            upDataList();
        }
        MkvUtils.get().putBoolean(MkvUtils.CommomData, CacheMarker.CacheForTheFirstTime, false);
        //判断是否首次进入并且缓存首次的状态
        boolean flag = getIntent().getBooleanExtra("isFirst", false);
        Intent intent = new Intent(PreferredChoiceActivity.this, MainActivity.class);
        intent.putExtra("checkId", mChannelId);
        intent.putExtra("isShowAd", flag);
        MainActivity.start(this, intent);
        finish();
    }

    /**
     * 对用户选择的新排序进行数据重组
     */
    private void upDataList() {
        List<ChannelEntity> dataList = new ArrayList<>();
        List<ChannelEntity> selectData = selectAdapter.getChannnelLst();
        List<ChannelEntity> otherData = otherAdapter.getChannnelLst();
        dataList.addAll(selectData);
        dataList.addAll(otherData);
        mChannelId = dataList.get(0).getId();
        //存储栏目顺序
        DatalUtils.getInstance().putData(MkvUtils.CommomData, CacheMarker.LocalHomePageTitle, dataList);
    }

    private void upDataList2() {
        mChannelId = jumpToList.get(0).getId();
        //存储栏目顺序
        DatalUtils.getInstance().putData(MkvUtils.CommomData, CacheMarker.LocalHomePageTitle, jumpToList);
    }

    public void getData(List<ChannelEntity> list) {
        if (list.size() > 0) {
            otherChannelList.clear();
            Iterator it = list.iterator();
            while (it.hasNext()) {
                ChannelEntity entity = (ChannelEntity)it.next();
                if (entity.getId() == 19) {
                    list.remove(entity);
                }
            }
            otherChannelList.addAll(list);
            jumpToList.addAll(otherChannelList);
            selectAdapter = new DragAdapter(this, selectlList);
            selectAdapter.setListener(new DragAdapter.ItemOnClickListener() {

                @Override
                public void onViewClick(ChannelEntity channel) {
                    if (TextUtils.isEmpty(channel.getIntroduce())) {
                        MToast.showToast(getActivity(), "暂无业务介绍");
                        return;
                    }
                    BusinessTipsDialog dialog = BusinessTipsDialog.newInstance(channel.getIntroduce());
                    dialog.showAllowingLoss(getSupportFragmentManager(), "channel");
                }

                @Override
                public void onDelete(View view, int position, ChannelEntity channel) {
                    final ImageView moveImageView = getView(view);
                    if (moveImageView != null) {
                        TextView newTextView = view.findViewById(R.id.text_item);
                        final int[] startLocation = new int[2];
                        newTextView.getLocationInWindow(startLocation);
                        otherAdapter.setVisible(false);
                        //添加到最后一个
                        otherAdapter.addItem(channel);
                        handler.postDelayed(() -> {
                            try {
                                int[] endLocation = new int[2];
                                //获取终点的坐标
                                binding.otherGridView.getChildAt(binding.otherGridView.getLastVisiblePosition()).getLocationInWindow(endLocation);
                                MoveAnim(moveImageView, startLocation, endLocation, channel, binding.selectGridView);
                                selectAdapter.setRemove(position);
                                if (selectAdapter.getCount() <= 1) {
                                    binding.btComplete.setSelected(false);
                                }
                            } catch (Exception localException) {
                            }
                        }, 30L);
                    }
                }

            });
            binding.selectGridView.setAdapter(selectAdapter);

            otherAdapter = new OtherAdapter(this, otherChannelList);
            otherAdapter.setListener(new OtherAdapter.ItemOnClickListener() {

                @Override
                public void onViewClick(ChannelEntity channel) {
                    if (TextUtils.isEmpty(channel.getIntroduce())) {
                        MToast.showToast(getActivity(), "暂无业务介绍");
                        return;
                    }
                    BusinessTipsDialog dialog = BusinessTipsDialog.newInstance(channel.getIntroduce());
                    dialog.showAllowingLoss(getSupportFragmentManager(), "channel");
                }

                @Override
                public void onDelete(View view, int position, ChannelEntity channel) {
                    final ImageView moveImageView1 = getView(view);
                    if (moveImageView1 != null) {
                        TextView newTextView = view.findViewById(R.id.text_item);
                        final int[] startLocation = new int[2];
                        newTextView.getLocationInWindow(startLocation);
                        selectAdapter.setVisible(false);
                        //添加到最后一个
                        selectAdapter.addItem(channel);
                        binding.btComplete.setSelected(true);
                        handler.postDelayed(() -> {
                            try {
                                int[] endLocation = new int[2];
                                //获取终点的坐标
                                binding.selectGridView.getChildAt(binding.selectGridView.getLastVisiblePosition()).getLocationInWindow(endLocation);
                                MoveAnim(moveImageView1, startLocation, endLocation, channel, binding.otherGridView);
                                otherAdapter.setRemove(position);
                            } catch (Exception localException) {
                            }
                        }, 30L);
                    }
                }

            });
            binding.otherGridView.setAdapter(otherAdapter);

            binding.btComplete.setVisibility(View.VISIBLE);
            //binding.jumpOver.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 获取点击的Item的对应View，
     *
     * @param view
     * @return
     */
    private ImageView getView(View view) {
        view.destroyDrawingCache();
        view.setDrawingCacheEnabled(true);
        Bitmap cache = Bitmap.createBitmap(view.getDrawingCache());
        view.setDrawingCacheEnabled(false);
        ImageView iv = new ImageView(this);
        iv.setImageBitmap(cache);
        return iv;
    }

    /**
     * 点击ITEM移动动画
     *
     * @param moveView
     * @param startLocation
     * @param endLocation
     * @param moveChannel
     * @param clickGridView
     */
    private void MoveAnim(View moveView, int[] startLocation, int[] endLocation, final ChannelEntity moveChannel,
                          final GridView clickGridView) {
        int[] initLocation = new int[2];
        //获取传递过来的VIEW的坐标
        moveView.getLocationInWindow(initLocation);
        //得到要移动的VIEW,并放入对应的容器中
        final ViewGroup moveViewGroup = getMoveViewGroup();
        final View mMoveView = getMoveView(moveViewGroup, moveView, initLocation);
        //创建移动动画
        TranslateAnimation moveAnimation = new TranslateAnimation(
                startLocation[0], endLocation[0], startLocation[1],
                endLocation[1]);
        moveAnimation.setDuration(300L);//动画时间
        //动画配置
        AnimationSet moveAnimationSet = new AnimationSet(true);
        moveAnimationSet.setFillAfter(false);//动画效果执行完毕后，View对象不保留在终止的位置
        moveAnimationSet.addAnimation(moveAnimation);
        mMoveView.startAnimation(moveAnimationSet);
        moveAnimationSet.setAnimationListener(new Animation.AnimationListener() {

            @Override
            public void onAnimationStart(Animation animation) {
                isMove = true;
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                moveViewGroup.removeView(mMoveView);
                // instanceof 方法判断2边实例是不是一样，判断点击的是DragGrid还是OtherGridView
                if (clickGridView instanceof DragGrid) {
                    otherAdapter.setVisible(true);
                    otherAdapter.notifyDataSetChanged();
                    selectAdapter.remove();
                } else {
                    selectAdapter.setVisible(true);
                    selectAdapter.notifyDataSetChanged();
                    otherAdapter.remove();
                }
                if (selectAdapter.getChannnelLst().size() > 0) {
                    binding.btComplete.setText("进入选择后经营帮");
                } else {
                    binding.btComplete.setText("默认经营帮展示");
                }
                isMove = false;
            }
        });
    }

    /**
     * 创建移动的ITEM对应的ViewGroup布局容器
     */
    private ViewGroup getMoveViewGroup() {
        ViewGroup moveViewGroup = (ViewGroup) getWindow().getDecorView();
        LinearLayout moveLinearLayout = new LinearLayout(this);
        moveLinearLayout.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        moveViewGroup.addView(moveLinearLayout);
        return moveLinearLayout;
    }

    /**
     * 获取移动的VIEW，放入对应ViewGroup布局容器
     *
     * @param viewGroup
     * @param view
     * @param initLocation
     * @return
     */
    private View getMoveView(ViewGroup viewGroup, View view, int[] initLocation) {
        int x = initLocation[0];
        int y = initLocation[1];
        viewGroup.addView(view);
        LinearLayout.LayoutParams mLayoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        mLayoutParams.leftMargin = x;
        mLayoutParams.topMargin = y;
        view.setLayoutParams(mLayoutParams);
        return view;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
    }
}
